/*
 * Copyright (c) 2018-2022, 四川蜀天梦图数据科技有限公司.
 * All rights reserved.
 */

package back_tracing

import "sort"

/* 回溯算法：全排列 I */
func backtrackI(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
	for i := 0; i < len(*choices); i++ {
		if !(*selected)[i] {
			choice := (*choices)[i]
			*state = append(*state, choice)
			(*selected)[i] = true
			backtrackI(state, choices, selected, res)
			(*selected)[i] = false
			*state = (*state)[:len(*state)-1]
		}
	}

	if len(*state) == len(*choices) {
		newState := append([]int{}, *state...)
		*res = append(*res, newState)
	}
}

/* 回溯算法：全排列 II */
func backtrackII(state *[]int, choices *[]int, selected *[]bool, res *[][]int) {
	// 当状态长度等于元素数量时，记录解
	if len(*state) == len(*choices) {
		newState := append([]int{}, *state...)
		*res = append(*res, newState)
	}
	// 遍历所有选择
	duplicated := make(map[int]bool, 0)
	for i := 0; i < len(*choices); i++ {
		choice := (*choices)[i]
		// 剪枝：不允许重复选择元素 且 不允许重复选择相等元素
		if _, ok := duplicated[choice]; !ok && !(*selected)[i] {
			// 尝试：做出选择，更新状态
			// 记录选择过的元素值
			duplicated[choice] = true
			(*selected)[i] = true
			*state = append(*state, choice)
			// 进行下一轮选择
			backtrackII(state, choices, selected, res)
			// 回退：撤销选择，恢复到之前的状态
			(*selected)[i] = false
			*state = (*state)[:len(*state)-1]
		}
	}
}

/* 全排列 I */
func permutationsI(nums []int) [][]int {
	res := make([][]int, 0)
	state := make([]int, 0)
	selected := make([]bool, len(nums))
	backtrackI(&state, &nums, &selected, &res)
	return res
}

func permutationsII(nums []int) [][]int {
	res := make([][]int, 0)
	state := make([]int, 0)
	selected := make([]bool, len(nums))
	backtrackII(&state, &nums, &selected, &res)
	return res
}

func backtrackSubsetSumINaive(total, target int, state, choices *[]int, res *[][]int) {
	if total == target {
		newState := append([]int{}, *state...)
		*res = append(*res, newState)
		return
	}

	for i := 0; i < len(*choices); i++ {
		choice := (*choices)[i]
		// 相比在开头写大于的判断条件，可以少进行一次栈递归
		if choice+total > target {
			continue
		}
		*state = append(*state, choice)
		total += choice
		backtrackSubsetSumINaive(total, target, state, choices, res)
		total -= (*state)[len(*state)-1]
		*state = (*state)[:len(*state)-1]
	}
}

// 新增start参数，每一次选择都从start及其后面开始选择，不选择之前的结果
func optimizeBacktrackSubsetSumINaive(start, total, target int, state, choices *[]int, res *[][]int) {
	if total == target {
		newState := append([]int{}, *state...)
		*res = append(*res, newState)
		return
	}

	for ; start < len(*choices); start++ {
		choice := (*choices)[start]
		// 相比在开头写大于的判断条件，可以少进行一次栈递归
		// 因为已经排序，下一次必定超过，可以直接退出本次循环
		if choice+total > target {
			break
		}
		*state = append(*state, choice)
		total += choice
		optimizeBacktrackSubsetSumINaive(start, total, target, state, choices, res)
		total -= (*state)[len(*state)-1]
		*state = (*state)[:len(*state)-1]
	}
}

func backtrackSubsetSumII(start, total, target int, state, choices *[]int, res *[][]int) {
	if total == target {
		newState := append([]int{}, *state...)
		*res = append(*res, newState)
		return
	}

	for ; start < len(*choices); start++ {
		choice := (*choices)[start]
		if start > 0 && choice == (*choices)[start-1] {
			continue
		}

		// 相比在开头写大于的判断条件，可以少进行一次栈递归
		// 因为已经排序，下一次必定超过，可以直接退出本次循环
		if choice+total > target {
			break
		}
		*state = append(*state, choice)
		total += choice
		optimizeBacktrackSubsetSumINaive(start, total, target, state, choices, res)
		total -= (*state)[len(*state)-1]
		*state = (*state)[:len(*state)-1]
	}
}

func subsetSumINaive(nums []int, target int) [][]int {
	state := make([]int, 0) // 状态（子集）
	total := 0              // 子集和
	res := make([][]int, 0) // 结果列表（子集列表）
	//backtrackSubsetSumINaive(total, target, &state, &nums, &res)
	sort.Ints(nums)
	optimizeBacktrackSubsetSumINaive(0, total, target, &state, &nums, &res)
	return res
}
